package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    StringRedisTemplate  stringRedisTemplate;
    @Resource
    CacheClient  cacheClient;
    @Override
    public Result queryById(Long id) {
        //方法一
        //1.从redis中查询店铺id

        //2.如果在redis中存在返回数据

        //3.如果redis中不存在，就去数据库中根据店铺id查找

        //4.如果数据库中存在，那么把数据返回，并且保存到redis当中

        //5.如果数据库中也不存在，直接返回401

        /*----------------------------------------*/
        //方法二
        //1.缓存空值解决缓存穿透
//        Shop  shop = queryWithPassThrough(id);
//        Shop  shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, Shop.class,id, CACHE_SHOP_TTL, TimeUnit.SECONDS,this::getById);
        //2.互斥锁解决缓存击穿
//       Shop  shop = queryWithMutex(id);
        Shop shop = cacheClient.queryWithMutex(CACHE_SHOP_KEY, id,Shop.class,this::getById,CACHE_NULL_TTL, TimeUnit.SECONDS,CACHE_SHOP_TTL);
        //3.逻辑过期解决缓存击穿
//        Shop  shop = queryWithLogicalExpire(id);
//        Shop  shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, Shop.class,id,this::getById,CACHE_SHOP_TTL, TimeUnit.SECONDS);
        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);

    }
    //创造线程池
//    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
//    public Shop queryWithLogicalExpire(Long id) {
          //1.查询商铺信息
//        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
          //2.判断是否在redis中是否存在
//        if (StrUtil.isBlank(shopJson)) {
              //3.如果不存在，直接返回null
//            return null;
//        }
          //4.如果存在，判断逻辑时间是否过期
//        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
//        JSONObject  data = (JSONObject) redisData.getData();
//        Shop shop =JSONUtil.toBean(data, Shop.class);
//        LocalDateTime expireTime = redisData.getExpireTime();
          //5.如果没有过期，直接返回商铺信息
//        if (expireTime.isAfter(LocalDateTime.now())) {
//            return shop;
//        }
          //6.如果过期了，尝试获取锁，更新逻辑时间
//        String lock = LOCK_SHOP_KEY + id;
//        if (tryLock(lock)) {
//            //获取锁成功，开启独立线程，实现缓存重建
//            try {
//                CACHE_REBUILD_EXECUTOR.submit(() -> {
//                    this.saveShop2Redis(id, 20L);
//                });
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            } finally {
                  //释放锁
//                releaseLock(lock);
//            }
//        }
          //返回数据
//        return shop;
//    }
//    public Shop queryWithMutex(Long id) {
//        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
//        if (StrUtil.isNotBlank(shopJson)) {
//            return JSONUtil.toBean(shopJson, Shop.class);
//        }
//        if (shopJson != null) {
//            return null;
//        }
//        //缓存重建
//        //获取互斥锁
//        //判断是否获取锁成功
//        //失败获取锁，休眠并重试
//        String lock = LOCK_SHOP_KEY + id;
//        Shop shop;
//        try {
//            if (!tryLock(lock)) {
//                Thread.sleep(50);
//                return queryWithMutex(id);
//            }
//            //获取锁成功，二次判断缓存是否存在
//            shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
//            if (StrUtil.isNotBlank(shopJson)) {
//                return JSONUtil.toBean(shopJson, Shop.class);
//            }
//            if (shopJson != null) {
//                return null;
//            }
//            //不存在，查询数据库
//            shop = getById(id);
//            if (shop == null) {
//                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
//                return null;
//            }
//            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        } finally {
//            releaseLock(lock);
//        }
//        return shop;
//    }
//    public Shop queryWithPassThrough(Long id){
          //1.从redis中查询商铺缓存
//        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
          //2.判断是否存在
//        if (StrUtil.isNotBlank(shopJson)) {
              //存在直接返回结果
//            return JSONUtil.toBean(shopJson, Shop.class);
//        }
          //3.判断获取的数据是否为空值
//        if (shopJson != null) {
              //不是空指针，那就是空字符串，直接返回null
//            return null;
//        }
          //4.根据id从数据库中查询
//        Shop shop = getById(id);
          //5.判断数据库中是否存在商铺信息
//        if (shop == null) {
              //如果不存在，创建一个空值存到redis当中
//            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
//            return null;
//        }
          //存在，更新redis中的缓存信息
//        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
            //返回数据
//        return shop;
//    }
//    private boolean tryLock(String key){
//        Boolean flag =stringRedisTemplate.opsForValue().setIfAbsent(key, "1",LOCK_SHOP_TTL, TimeUnit.SECONDS);
//        return Boolean.TRUE.equals(flag);
//    }
//    private void releaseLock(String key){
//        stringRedisTemplate.delete(key);
//    }
//    public void saveShop2Redis(Long id,Long expireSeconds){
          //1.查询店铺信息
//        Shop shop = getById(id);
//        RedisData redisData = new RedisData();
          //2.封装逻辑过期时间和店铺信息
//        redisData.setData(shop);
//        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
          //3.写入redis中
//        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
//    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }
        //1.  更新数据库
        updateById(shop);
        //2. 删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    public Result queryShopById(Integer typeId, Integer current, Double x, Double y) {
        //1.判断是否需要坐标信息
        if (x == null || y == null) {
            //不需要坐标，按照数据库查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }
        //2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        //3.查询redis，按照距离排序，分页。结果：shopId，distance
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );
        //4.解析出Id
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页，结束
            return Result.ok(Collections.emptyList());
        }
        //4.1.截取from~end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String,Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            //4.2.获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            //4.3.获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr,distance);
        });
        //5.根据id查询shop
        String idStr = StrUtil.join(",",ids);
        List<Shop> shops = query()
                .in("id", ids).last("order by field(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        //6.封装结果返回
        return Result.ok(shops);
    }
}
